<template>
  <!-- 顶部搜索区域，按钮区域 -->
  <div>
    <el-card class="box-card">
      <el-row>
        <el-col :span="6">
          订单编号：<el-input
            v-model="serachModel.orderNumber"
            placeholder="订单编号"
            clearable
            style="width: 280px; margin-right: 10px"
          ></el-input>
        </el-col>
        <el-col :span="6">
          收货手机号：<el-input
            v-model="serachModel.phone"
            placeholder="收货手机号"
            clearable
            style="width: 180px; margin-right: 10px"
          ></el-input>
        </el-col>

        <el-col :span="6">
          发货日期：
          <el-date-picker
            v-model="serachModel.deliveryDate"
            type="date"
            placeholder="选择日期"
            style="width: 180px; margin-right: 10px"
            width="180px"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          >
          </el-date-picker>
        </el-col>
        <el-col :span="6">
          排序方式：
          <el-select
            v-model="serachModel.orderByDesc"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <!-- 按钮区域 -->
        <el-col :span="12" style="margin-top: 10px">
          <el-button type="primary" @click="getOrderList">查询</el-button>

          <el-button
            v-if="orderStatus == '待点发货'"
            type="primary"
            @click="openTransferUi"
            >序列号出库</el-button
          >

          <el-button
            v-if="orderStatus == '待发货'"
            type="warning"
            @click="updateStatus('发货中')"
            >批量添加到发货中</el-button
          >
          <!--  v-if="orderStatus === '待发货'" -->
          <el-button
            type="primary"
            style="margin-right: 10px"
            @click="OpenGoodsUi"
            >更新库存状态</el-button
          >

          <el-button
            v-if="orderStatus == '发货中'"
            type="warning"
            @click="updateStatus('待点发货')"
            >批量添加到待点发货中</el-button
          >
        </el-col>
        <el-col
          :span="12"
          v-if="orderStatus == '待点发货'"
          align="right"
          style="margin-top: 10px"
        >
        </el-col>
        <el-col
          :span="12"
          align="right"
          style="margin-top: 10px"
          v-if="orderStatus == '发货中'"
        >
          <el-button type="primary" @click="OpenSendGoodsUi">备 货</el-button>
          <el-button type="primary" @click="exportSendOrder"
            >导出发货表</el-button
          >
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-tabs v-model="orderStatus" @tab-click="handleClick">
        <el-tab-pane label="待发货" name="待发货"></el-tab-pane>
        <el-tab-pane label="发货中" name="发货中"></el-tab-pane>
        <el-tab-pane label="待点发货" name="待点发货"></el-tab-pane>
      </el-tabs>
      <el-table
        :data="orderList"
        style="width: 100%"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="50"> </el-table-column>

        <el-table-column prop="creditRating" label="订单信息" width="280" fixed>
          <template slot-scope="scope">
            标记记录：<span style="color: #f56c6c"
              >{{ scope.row.creditRating }}
            </span>
            <br />
            <span>平台：{{ scope.row.orderPlatform }} </span>
            <br />
            <!-- 判断是否有重复订单编号 -->
            <el-badge is-dot v-if="isExist(scope.row.orderLogs, 'orderNumber')">
              <span
                >订单编号：<el-button
                  type="text"
                  class="btn-copy"
                  :data-clipboard-text="scope.row.orderNumber"
                  @click="copyMessage()"
                  >{{ scope.row.orderNumber }}</el-button
                >
              </span>
            </el-badge>
            <span v-else
              >订单编号：<el-button
                type="text"
                class="btn-copy"
                :data-clipboard-text="scope.row.orderNumber"
                @click="copyMessage()"
                >{{ scope.row.orderNumber }}</el-button
              >
            </span>
            <br />
            型号：<strong>{{ scope.row.tradeName }}</strong>
            <br />
            套餐：<strong>{{ scope.row.setMeal }}</strong>
            <br />
            配件：<strong>{{ scope.row.attachment }}</strong>
            <br />
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="OpenEditUi(scope.row.id, 'orderInfo')"
              >编辑</el-button
            >
          </template>
        </el-table-column>

        <el-table-column label="发货信息" width="240">
          <template slot-scope="scope">
            发货日：
            <span
              v-if="
                scope.row.deliveryDate != null &&
                scope.row.deliveryDate != undefined
              "
            >
              <span v-if="isDateBeforeToday(scope.row.deliveryDate)">{{
                scope.row.deliveryDate
                  .split(" ")[0]
                  .substring(0, scope.row.deliveryDate.split("T")[0].length)
              }}</span>
              <span style="color: #f56c6c" v-else>
                {{
                  scope.row.deliveryDate
                    .split(" ")[0]
                    .substring(0, scope.row.deliveryDate.split("T")[0].length)
                }}
              </span>
              <br />
              运费：
              <span>
                {{ scope.row.freight }}
              </span>
              <br />
              寄出单号：
              <strong>
                {{ scope.row.trackingNumber }}
              </strong>
              <br />
              寄回单号：
              <strong>
                {{ scope.row.receiptNumber }}
              </strong>
              <br />
              签收单号：
              <strong>
                {{ scope.row.getReceiptNumber }}
              </strong>

              <br />
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="OpenEditUi(scope.row.id, 'sendInfo')"
                >编辑</el-button
              >
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="serialNumbers"
          label="序列号"
          v-if="orderStatus != '待发货'"
        >
          <template slot-scope="scope">
            <div
              :key="index"
              v-for="(snumber, index) in scope.row.serialNumbers"
            >
              <el-tag
                closable
                :disable-transitions="false"
                @close="deleteSNumberById(snumber)"
              >
                {{ snumber.serialNumber }}-<span v-if="snumber.status">
                  已出库
                </span>
                <span v-else>待出库</span>
              </el-tag>
            </div>

            <el-button
              icon="el-icon-plus"
              circle
              size="mini"
              @click="SerivalNumUi(null, scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" width="260">
          <template slot-scope="scope">
            <div
              v-show="!scope.row.remarkEdit"
              @click="scope.row.remarkEdit = !scope.row.remarkEdit"
            >
              {{
                scope.row.remark == null || scope.row.remark.trim() == ""
                  ? "......"
                  : scope.row.remark
              }}
            </div>

            <div v-show="scope.row.remarkEdit">
              <el-input v-model="scope.row.remark"></el-input>
              <el-button type="text" @click="updateOrderRemark(scope.row)"
                >保存</el-button
              >
              <el-button type="text" @click="getOrderList()">取消</el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="" label="租期" width="180">
          <template slot-scope="scope">
            <strong style="font-size: 14px">
              {{
                startAndEndTime(scope.row.startTime, scope.row.endTime)
              }}</strong
            >
            <br />
            <strong v-if="scope.row.duration >= 90" style="color: #f56c6c">
              {{ durationAndMoney(scope.row.duration, scope.row.money) }}
            </strong>
            <strong v-else>
              {{ durationAndMoney(scope.row.duration, scope.row.money) }}
            </strong>
            <br />
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="OpenEditUi(scope.row.id, 'rentTimeInfo')"
              >编辑</el-button
            >
          </template>
        </el-table-column>

        <el-table-column label="客户收货信息" width="360">
          <template slot-scope="scope">
            <span>收 件 人：</span><strong>{{ scope.row.userName }}</strong>
            <span style="padding: 6px"></span>
            <br />
            <span>手 机 号：</span
            ><el-badge
              is-dot
              class="item"
              v-if="isExist(scope.row.orderLogs, 'userinfo')"
              ><el-button
                type="text"
                class="btn-copy"
                :data-clipboard-text="scope.row.phone"
                @click="copyMessage()"
                ><strong>{{ scope.row.phone }}</strong></el-button
              ></el-badge
            >
            <el-button
              v-else
              type="text"
              class="btn-copy"
              :data-clipboard-text="scope.row.phone"
              @click="copyMessage()"
              ><strong>{{ scope.row.phone }}</strong></el-button
            >
            <br />
            <el-row
              ><el-col :span="5">收件地址：</el-col
              ><el-col :span="19">
                <strong>{{ scope.row.address }}</strong></el-col
              ></el-row
            >

            <br />
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="OpenEditUi(scope.row.id, 'userInfo')"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="btn-copy"
              :data-clipboard-text="getAddressInfo(scope.row)"
              @click="copyMessage()"
              >复制收货信息</el-button
            >
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.debitStatus != '已扣款'" type="warning">{{
              scope.row.debitStatus
            }}</el-tag>

            <br />
            <span v-if="scope.row.stockStatus != '已减库存'">
              <el-tag v-if="scope.row.stockStatus == '没有库存'" type="danger">
                {{ scope.row.stockStatus }}
              </el-tag>
              <el-tag v-else>{{ scope.row.stockStatus }}</el-tag>
            </span>

            <br />
            <el-tag v-if="scope.row.addressStatus != '正常'" type="warning">{{
              scope.row.addressStatus
            }}</el-tag>

            <br />
          </template>
        </el-table-column>
        <!-- 日志 -->
        <el-table-column label="订单日志">
          <template slot-scope="scope">
            <!-- 显示两天最新的日志 -->
            <div v-if="scope.row.orderLogs.length > 0">
              <el-popover
                placement="left"
                title="订单日志"
                width="520"
                trigger="hover"
              >
                <el-timeline>
                  <el-timeline-item
                    v-for="(logs, index) in scope.row.orderLogs"
                    :key="index"
                    :timestamp="logs.createTime"
                    :color="logs.type == false ? '#909399' : '#409EFF'"
                  >
                    <span>{{ logs.operator }}</span>
                    <span
                      v-if="
                        logs.log === '补发订单' ||
                        logs.log === '重复订单' ||
                        logs.log === '转寄订单'
                      "
                      style="color: #f56c6c"
                    >
                      {{ logs.log }}</span
                    >
                    <span v-else> {{ logs.log }}</span>
                  </el-timeline-item>
                </el-timeline>

                <el-badge
                  v-if="getSpecialOrderNum(scope.row.orderLogs) > 0"
                  :value="getSpecialOrderNum(scope.row.orderLogs)"
                  class="item"
                  slot="reference"
                  style="margin-top: 10px"
                >
                  <el-button type="text">
                    <strong>{{ scope.row.orderLogs[0].log }}</strong>
                  </el-button>
                </el-badge>
                <el-button type="text" slot="reference" v-else>
                  <strong>{{ scope.row.orderLogs[0].log }}</strong>
                </el-button>
              </el-popover>
              <!-- 添加日志时间 -->
              <div>
                <span style="margin-right: 6px">{{
                  scope.row.orderLogs[0].operator
                }}</span
                ><span>{{ scope.row.orderLogs[0].createTime }}</span>
              </div>
            </div>

            <el-button type="text" @click="openAddlogUi(scope.row)"
              >添加日志</el-button
            >
          </template>
        </el-table-column>
        <!-- 状态 -->

        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-dropdown trigger="click" @command="handleCommand">
                  <el-button type="primary" size="mini">
                    订单状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '订单处理',
                      }"
                      >订单处理</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '待发货',
                      }"
                      >待发货</el-dropdown-item
                    >

                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '待取消',
                      }"
                      >待取消</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>

                <el-dropdown
                  trigger="click"
                  style="margin-top: 6px"
                  @command="handleCommand"
                >
                  <el-button type="primary" size="mini">
                    库存状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'stockStatus',
                        status: '未减库存',
                      }"
                      >未减库存</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'stockStatus',
                        status: '已减库存',
                      }"
                      >已减库存</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'stockStatus',
                        status: '没有库存',
                      }"
                      >没有库存</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>

                <el-dropdown
                  trigger="click"
                  style="margin-top: 6px"
                  @command="handleCommand"
                >
                  <el-button type="primary" size="mini">
                    地址状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'addressStatus',
                        status: '正常',
                      }"
                      >正常</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'addressStatus',
                        status: '地址需核实',
                      }"
                      >地址需核实</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'addressStatus',
                        status: '收货秘钥',
                      }"
                      >收货秘钥</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>

                <el-dropdown
                  trigger="click"
                  style="margin-top: 6px"
                  @command="handleCommand"
                >
                  <el-button type="primary" size="mini">
                    扣款状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'debitStatus',
                        status: '未扣款',
                      }"
                      >未扣款</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'debitStatus',
                        status: '已扣款',
                      }"
                      >已扣款</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
              <el-col :span="12">
                <el-button
                  v-if="scope.row.orderStatus === '待发货'"
                  size="mini"
                  style="margin-top: 10px"
                  @click="
                    updateOrderStatus({
                      id: scope.row.id,
                      model: 'orderStatus',
                      status: '发货中',
                    })
                  "
                  >发 货</el-button
                >
                <el-button
                  v-if="scope.row.orderStatus === '发货中'"
                  size="mini"
                  style="margin-top: 10px"
                  @click="
                    updateOrderStatus({
                      id: scope.row.id,
                      model: 'orderStatus',
                      status: '待点发货',
                    })
                  "
                  >已备货</el-button
                >
                <el-button
                  v-if="scope.row.orderStatus == '待点发货'"
                  size="mini"
                  style="margin-top: 10px"
                  @click="
                    updateOrderStatus({
                      id: scope.row.id,
                      model: 'orderStatus',
                      status: '已发货',
                    })
                  "
                  >已发货</el-button
                >
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="serachModel.pageNo"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="serachModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 编辑订单对话 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="cleaForm"
      :before-close="handleClose"
      width="820px"
    >
      <el-form
        :model="orderForm"
        class="demo-form-inline"
        ref="orderFormRef"
        :rules="rules"
      >
        <el-row v-if="EditUiType.orderInfo">
          <el-form-item label="标记记录" :label-width="formLabelWidth">
            <el-input
              v-model="orderForm.creditRating"
              placeholder="标记记录"
            ></el-input>
          </el-form-item>
          <el-form-item label="平台" :label-width="formLabelWidth">
            <el-input
              v-model="orderForm.orderPlatform"
              placeholder="平台"
            ></el-input>
          </el-form-item>
          <el-form-item
            id=""
            label="订单编号"
            prop="orderNumber"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.orderNumber"
              autocomplete="off"
              placeholder="订单编号"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="型 号"
            prop="tradeName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.tradeName"
              autocomplete="off"
              placeholder="型 号"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="商品名称"
            prop="setMeal"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.setMeal"
              autocomplete="off"
              placeholder="商品名称"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="配件"
            prop="attachment"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.attachment"
              autocomplete="off"
              placeholder="配件"
            ></el-input
          ></el-form-item>
        </el-row>

        <el-row v-if="EditUiType.sendInfo">
          <el-form-item
            label="时 效"
            prop="ageing"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model.number="orderForm.ageing"
              label="时 效"
              placeholder="时 效"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="运 费"
            prop="freight"
            :label-width="formLabelWidth"
          >
            <el-select v-model="orderForm.freight" placeholder="运费">
              <el-option label="寄 付" value="寄付"></el-option>
              <el-option label="包 邮" value="包邮"></el-option>
              <el-option label="到 付" value=""></el-option>
              <el-option label="特快寄付" value="特快寄付"></el-option>
              <el-option label="特快到付" value="特快到付"></el-option>
            </el-select>
          </el-form-item>

          <!-- 单号 -->
          <!-- 寄出单号 -->
          <el-form-item
            label="寄出单号"
            prop="trackingNumber"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.trackingNumber"
              label="寄出单号"
              placeholder="寄出单号"
            ></el-input
          ></el-form-item>
          <!-- 寄回单号 -->
          <el-form-item
            label="寄回单号"
            prop="receiptNumber"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.receiptNumber"
              label="寄回单号"
              placeholder="寄回单号"
            ></el-input
          ></el-form-item>
          <!-- 签收单号 -->
          <el-form-item
            label="签收单号"
            prop="getReceiptNumber"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.getReceiptNumber"
              label="签收单号"
              placeholder="签收单号"
            ></el-input
          ></el-form-item>
        </el-row>
        <el-row v-if="EditUiType.remarkInfo">
          <el-form-item
            label="备 注"
            prop="remark"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="orderForm.remark"
            >
            </el-input>
          </el-form-item>
        </el-row>

        <el-row v-if="EditUiType.rentTimeInfo">
          <el-form-item label="起租日" :label-width="formLabelWidth">
            <el-date-picker
              v-model="orderForm.startTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            label="天数"
            prop="duration"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model.number="orderForm.duration"
              autocomplete="off"
              placeholder="天数"
            ></el-input>
          </el-form-item>

          <el-form-item label="租金" prop="money" :label-width="formLabelWidth">
            <el-input
              v-model.number="orderForm.money"
              autocomplete="off"
              placeholder="租金"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row v-if="EditUiType.userInfo">
          <el-form-item
            label="收 件 人"
            prop="userName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.userName"
              autocomplete="off"
              placeholder="收件人"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="收货手机号"
            prop="phone"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.phone"
              autocomplete="off"
              placeholder="收货手机号"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="收货地址"
            prop="address"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.address"
              autocomplete="off"
              placeholder="收货地址"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrder()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 序列号对话框 -->
    <el-dialog
      :title="SerivalNumtitle"
      :visible.sync="dialogFormVisibleSerivalNum"
      @close="cleaForm"
      :before-close="handleClose"
    >
      <el-form
        :model="SerialNumForm"
        class="demo-form-inline"
        ref="SerialNumFormRef"
        :rules="SerialNumFormRules"
      >
        <el-form-item
          label="序列号"
          prop="serialNumber"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="SerialNumForm.serialNumber"
            autocomplete="off"
            placeholder="序列号"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleSerivalNum = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="saveSerivalNum">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 自定义日志 -->
    <el-dialog
      title="自定义日志"
      :visible.sync="dialogVisibleLog"
      width="520px"
      :before-close="handleClose"
      @close="clearLogForm"
    >
      <el-form label-width="80px" :model="userLogForm">
        <el-form-item label="订单类型">
          <el-checkbox-group v-model="userLogForm.types">
            <el-checkbox label="补发订单" name="type"></el-checkbox>
            <el-checkbox label="重复订单" name="type"></el-checkbox>
            <el-checkbox label="转寄订单" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="输入日志">
          <el-input
            type="textarea"
            :rows="4"
            v-model="userLogForm.log"
            width="400"
            maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLog = false">取 消</el-button>
        <el-button type="primary" @click="addUserLog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 备货对话框 -->
    <el-dialog
      title="备货"
      :visible.sync="dialogVisibleLogSendGoods"
      width="90%"
      :before-close="handleClose"
      @close="clearSendGoodsList"
    >
      <el-form id="table-form" ref="form">
        <el-table :data="sendGoodsList" style="width: 100%">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column prop="tradeName" label="型号" width="180">
          </el-table-column>

          <el-table-column prop="setMeal" label="套餐" width="460">
          </el-table-column>

          <el-table-column label="配件" width="180">
            <template slot-scope="scope">
              <strong>{{ scope.row.attachment }}</strong>
            </template>
          </el-table-column>

          <el-table-column label="序列号" width="260">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.serialNumber"
                placeholder="序列号"
                style="margin-right: 20px"
                @blur="updateSerialNumber(scope.row)"
                @keyup.native.enter="nextFocus($event, scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="寄出单号" width="260">
            <template slot-scope="scope">
              <el-input
                :ref="scope.row.id"
                v-model="scope.row.trackingNumber"
                placeholder="运单号"
                style="margin-right: 20px"
                @blur="updateTrackingNumber(scope.row)"
                @keyup.native.enter="nextFocus($event, scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注" width="180">
          </el-table-column>
          <el-table-column prop="userName" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="phone" label="电话" width="180">
          </el-table-column>
          <el-table-column prop="address" label="地址"> </el-table-column>
        </el-table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLogSendGoods = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 序列号出库对话框 -->
    <el-dialog
      title="序列号出库"
      :visible.sync="dialogVisibleLogOutWarehouse"
      width="60%"
      :before-close="handleClose"
      @close="clearTransferData"
    >
      <div align="center">
        <el-row>
          <el-col :span="12">
            调出仓库：
            <el-select
              v-model="transGoodsForm.outWarehouseId"
              filterable
              placeholder="调出仓库"
              style="margin: 10px"
              @change="getInWarehouseNum"
              clearable
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            调入仓库：
            <el-select
              v-model="transGoodsForm.saveWarehouseId"
              filterable
              placeholder="调入仓库"
              style="margin: 10px"
              clearable
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-tabs
            type="border-card"
            v-model="activeName"
            v-loading="transferLoading"
          >
            <el-tab-pane :label="getTableName('在库')" name="first">
              <el-table :data="transGoodsForm.inWarehouseSerialNumber">
                <el-table-column
                  prop="serialNumber"
                  label="序列号"
                ></el-table-column>
                <el-table-column
                  prop="productName"
                  label="商品名称"
                ></el-table-column>
                <el-table-column
                  prop="warehouseName"
                  label="所在仓库"
                ></el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane :label="getTableName('不在库')" name="second">
              <el-table :data="transGoodsForm.outWarehouseSerialNumber">
                <el-table-column
                  prop="serialNumber"
                  label="序列号"
                ></el-table-column>
                <el-table-column
                  prop="productName"
                  label="商品名称"
                ></el-table-column>
                <el-table-column
                  prop="warehouseName"
                  label="所在仓库"
                ></el-table-column>

                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      @click="updateSerialNumberStatus(scope.row)"
                      >已出库</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLogOutWarehouse = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="transferSerialNumber"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 批量减库存对话框 -->
    <el-dialog
      title="更新库存"
      :visible.sync="dialogTableVisibleGoods"
      :before-close="handleClose"
      @close="clearGoods"
    >
      <el-row>
        <el-col :span="12">
          库存状态：
          <el-select
            v-model="seleceStatusCode"
            placeholder="请选择"
            @change="OpenGoodsUi"
          >
            <el-option
              v-for="item in stockStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.value == statusCode ? true : false"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="12">
          更新库存状态：
          <el-select v-model="statusCode" placeholder="请选择" clearable>
            <el-option
              v-for="item in stockStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.value == seleceStatusCode ? true : false"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-tabs v-model="activeName" type="card" style="margin-top: 10px">
          <el-tab-pane label="设备列表" name="first">
            <el-table
              :data="GoodsList"
              ref="singleTable"
              @selection-change="handleSelectionChangeGoodsList"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="orderPlatform" label=" 平 台" width="80">
              </el-table-column>
              <el-table-column prop="orderNumber" label="订单编号" width="200">
                <template slot-scope="scope">
                  <span>
                    <el-link
                      :underline="false"
                      class="btn-copy"
                      :data-clipboard-text="scope.row.orderNumber"
                      @click="copyMessage()"
                      >{{ scope.row.orderNumber }}</el-link
                    >
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="tradeName" label="型号" width="180">
              </el-table-column>

              <el-table-column prop="userName" label="姓名" width="90">
              </el-table-column>
              <el-table-column prop="phone" label="电话" width="180">
              </el-table-column>
              <el-table-column prop="address" label="地址"> </el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click.native.prevent="deleteRow(scope.$index, GoodsList)"
                    >删 除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="设备统计" name="second">
            <el-card class="box-card">
              <div
                v-for="(value, key) in getGoodsListSum"
                :key="key"
                style="margin-top: 10px"
              >
                {{ key }} : {{ value }}
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-row>

      <el-row>
        <el-col align="right" style="margin-top: 16px; margin-right: 20px">
          <el-button type="primary" size="smell" @click="updateStockStatus()"
            >确 定</el-button
          >
          <el-button @click="dialogTableVisibleGoods = false" size="smell"
            >取 消</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from "@/api/order";
import serivalNumberApi from "@/api/SerialNumber";
import orderLogApi from "@/api/orderLog";
import ClipboardJS from "clipboard"; // 复制
import { getToken } from "@/utils/auth";
import warehouseApi from "@/api/inventory/warehouse";
import inventoryApi from "@/api/inventory/inventory";

export default {
  mounted() {
    new ClipboardJS(".btn-copy"); // 复制文本
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      var reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!reg.test(value)) {
        return callback(new Error("手机格式错误"));
      }
      callback();
    };

    var checkSerilNum = (rule, value, callback) => {
      var reg =
        /^(?=.*[0-9a-zA-Z-])(?=.{4,20}$)(?:(?=.*\d)|(?=.*-))[0-9a-zA-Z-]*$/;
      if (value.length > 26 || value.length < 4) {
        return callback(new Error("序列号长度不对(4-26个字符)"));
      }
      if (!reg.test(value)) {
        return callback(new Error("序列号不合法"));
      }
      callback();
    };
    return {
      // 更新库存状态
      dialogTableVisibleGoods: false,

      dialogVisibleLogSendGoods: false,
      sendGoodsList: [],
      multipleSelectionGoodsList: [],

      GoodsList: [],
      GoodsSum: {},

      // 库存状态
      stockStatus: [
        {
          value: "未减库存",
          label: "未减库存",
        },
        {
          value: "已减库存",
          label: "已减库存",
        },
        {
          value: "没有库存",
          label: "没有库存",
        },
      ],

      // 序列号
      SerialNumForm: {},
      SerivalNumtitle: "",
      dialogFormVisibleSerivalNum: false,

      // 订单状态
      orderStatus: "待发货",

      formLabelWidth: "130px",

      loading: false,
      // 对话框标题
      title: "",
      // 对话框是否可见
      dialogFormVisible: false,

      total: 0,
      serachModel: {
        pageNo: 1,
        pageSize: 20,
      },
      orderForm: {},
      orderList: [],
      // 复选框
      multipleSelection: [],

      seleceStatusCode: "未减库存",
      statusCode: "",
      // 排序方式
      options: [
        {
          value: "平台",
          label: "平台",
        },
        {
          value: "发货日",
          label: "发货日",
        },
        {
          value: "型号",
          label: "型号",
        },
        {
          value: "起租日",
          label: "起租日",
        },
      ],

      rules: {
        tradeName: [
          { required: true, message: "请输入型号", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "长度在 2 到 100 个字符",
            trigger: "blur",
          },
        ],
        setMeal: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 255,
            message: "长度在 2 到 255 个字符",
            trigger: "blur",
          },
        ],
        userName: [
          { required: true, message: "请输入收件人", trigger: "blur" },
          {
            min: 1,
            max: 26,
            message: "长度在 1 到 26 个字符",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "请输入收货地址", trigger: "blur" },
          {
            min: 12,
            max: 255,
            message: "长度在 12 到 255 个字符",
            trigger: "blur",
          },
        ],

        phone: [{ validator: checkPhone, trigger: "blur" }],
        money: [{ type: "number", message: "请输入正确的金额" }],
        duration: [
          {
            type: "number",
            message: "请输入正确的租期天数",
          },
        ],
        trackingNumber: [
          {
            max: 40,
            message: "不能超过40个字符",
            trigger: "blur",
          },
        ],
        receiptNumber: [
          {
            max: 40,
            message: "不能超过40个字符",
            trigger: "blur",
          },
        ],
        getReceiptNumber: [
          {
            max: 40,
            message: "不能超过40个字符",
            trigger: "blur",
          },
        ],
      },

      SerialNumFormRules: {
        serialNumber: [{ validator: checkSerilNum, trigger: "blur" }],
      },

      // 对话框显示类型
      EditUiType: {
        orderInfo: false,
        sendInfo: false,
        remarkInfo: false,
        rentTimeInfo: false,
        userInfo: false,
        statusInfo: false,
      },

      userLogForm: {
        types: [],
      },

      dialogVisibleLog: false,

      // 修改模式
      model: "",

      inputDoms: [],

      // 查询序列号状态数据
      transferData: {
        serialNumbers: [],
      },
      dialogVisibleLogOutWarehouse: false,

      transGoodsForm: {
        inWarehouseSerialNumber: [],
        outWarehouseSerialNumber: [],
      },

      transferLoading: false,

      isWarehouseName: "在库(0)",
      outWarehouseName: "不在库(0)",

      activeName: "first",

      // 仓库名称
      allwareHouseName: [],
      // 备货对话框
    };
  },

  methods: {
    // 清空库存调拨数据
    clearTransferData() {
      this.transferData = {
        serialNumbers: [],
      };

      this.transGoodsForm = {
        inWarehouseSerialNumber: [],
        outWarehouseSerialNumber: [],
      };

      this.transferLoading = false;

      this.isWarehouseName = "在库(0)";
      this.outWarehouseName = "不在库(0)";

      this.activeName = "first";
    },
    initInputDOM() {
      //获取id为table-form下的所有input 框
      const inputDoms = document.querySelectorAll(
        "#table-form .el-input__inner"
      );
      //遍历这个input框给他们一个标识
      inputDoms.forEach((item, index) => {
        item.setAttribute("data-index", index);
      });
      this.inputDoms = inputDoms;
    },

    // 清除表单数据
    clearGoods() {
      this.activeName = "first";
      // 勾选的设备（{设备名称，客户信息}）
      this.GoodsList = [];

      //  设备求和({设备名称：数量})
      this.GoodsSum = {};
    },

    // 清空自定义日志对话框
    clearLogForm() {
      // 自定义日志
      // 清空表单数据
      this.userLogForm = {
        types: [],
      };
    },

    clearSendGoodsList() {
      this.sendGoodsList = [];
      // 更新表格
      this.getOrderList();
    },
    // 确认关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    handleSelectionChangeGoodsList(val) {
      this.multipleSelectionGoodsList = val;
    },

    handleSizeChange(pageSize) {
      this.serachModel.pageSize = pageSize;
      this.getOrderList();
    },
    handleCurrentChange(pageNo) {
      this.serachModel.pageNo = pageNo;
      this.getOrderList();
    },
    // 清理表单数据
    cleaForm() {
      // 清理数据
      this.orderForm = {};

      if (
        this.$refs.orderFormRef != null &&
        this.$refs.orderFormRef != undefined
      ) {
        this.$refs.orderFormRef.clearValidate();
      }
      this.SerialNumForm = {};
    },

    getOrderList() {
      this.loading = true;
      orderApi
        .getOrderList(this.serachModel, this.orderStatus)
        .then((response) => {
          // 给获取的List加一个字段
          this.addEdit(response.data.rows);
          this.total = response.data.total;
          this.loading = false;
        });
    },

    addEdit(orderList) {
      orderList.forEach((item) => {
        item.remarkEdit = false;
      });

      this.orderList = orderList;
    },

    // 更新订单备注
    updateOrderRemark(order) {
      var model = "remarkInfo";
      var pushOrder = {
        id: order.id,
        orderNumber: order.orderNumber,
        remark: order.remark,
        orderStatus: order.orderStatus,
        stockStatus: order.stockStatus,
        debitStatus: order.debitStatus,
        addressStatus: order.addressStatus,
        startTime: order.startTime,
        ageing: order.ageing,
      };
      // 提交数据给后台
      orderApi.saveOrder(pushOrder, model).then((response) => {
        this.$message({
          showClose: true,
          message: response.message,
          type: "success",
        });
        // 刷新表单
        this.getOrderList();
      });
    },

    handleSelectionChange(val) {
      // 保存选中的对象
      this.multipleSelection = val;
    },

    // 租期框计算
    startAndEndTime(startTime, endTime) {
      if (
        (startTime != null || startTime != undefined) &&
        (endTime != null || endTime != undefined)
      )
        return startTime.substring(5, 10) + "-" + endTime.substring(5, 10);
      else return null;
    },

    durationAndMoney(duration, money) {
      if (
        (duration != null || duration != undefined) &&
        (money != null || money != undefined)
      )
        return duration + "天," + money + "元";
    },

    // 添加订单
    saveOrder() {
      this.$refs.orderFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 提交数据给后台
          orderApi.saveOrder(this.orderForm, this.model).then((response) => {
            if (response.code == 20000) {
              this.$message({
                showClose: true,
                message: response.message,
                type: "success",
              });
              // 关闭对话框
              this.dialogFormVisible = false;
              // 刷新表单
              this.getOrderList();
              this.loading = false;
            } else {
              this.$notify({
                title: "警告",
                message: response.message,
                type: "warning",
                duration: 0,
              });
              // 关闭对话框
              this.dialogFormVisible = false;
              // 刷新表单
              this.getOrderList();
              this.loading = false;
            }
          });
        } else {
          // 验证不通过
          this.$message({
            showClose: true,
            message: "表单验证不通过",
            type: "error",
          });
          this.loading = false;
          return false;
        }
      });
    },

    // 显示对话框
    OpenEditUi(orderId, type) {
      if (type != null && type != undefined) {
        // 订单信息
        if (type == "orderInfo") {
          this.EditUiType = {
            orderInfo: true,
            sendInfo: false,
            remarkInfo: false,
            rentTimeInfo: false,
            userInfo: false,
            statusInfo: false,
          };
        } else if (type == "sendInfo") {
          // 发货信息
          this.EditUiType = {
            orderInfo: false,
            sendInfo: true,
            remarkInfo: false,
            rentTimeInfo: false,
            userInfo: false,
            statusInfo: false,
          };
        } else if (type == "rentTimeInfo") {
          // 租期信息
          this.EditUiType = {
            orderInfo: false,
            sendInfo: false,
            remarkInfo: false,
            rentTimeInfo: true,
            userInfo: false,
            statusInfo: false,
          };
        } else if (type == "userInfo") {
          // 客户信息
          this.EditUiType = {
            orderInfo: false,
            sendInfo: false,
            remarkInfo: false,
            rentTimeInfo: false,
            userInfo: true,
            statusInfo: false,
          };
        }
      }

      if (orderId == null || orderId == undefined) {
        this.title = "添加订单";
        this.dialogFormVisible = true;
      } else {
        this.title = "修改订单";
        this.loading = true;
        orderApi.getOrderById(orderId).then((response) => {
          this.orderForm = response.data;
          this.loading = false;
        });

        this.model = type;
        this.loading = false;
        this.dialogFormVisible = true;
      }
    },

    // 发货日处理
    isDateBeforeToday(dateStr) {
      const inputDate = new Date(dateStr); // 创建输入日期的 JavaScript Date 对象
      const today = new Date(); // 获取今天的日期的 JavaScript Date 对象

      // 只比较日期部分，不比较时间，将时分秒都设置为 0
      inputDate.setHours(0, 0, 0, 0);
      today.setHours(0, 0, 0, 0);

      return inputDate >= today; // 比较日期
    },

    // 导出发货表
    exportSendOrder() {
      // 获取所有被选中的ID
      var exprotIds = "";
      if (
        this.multipleSelection[0] != null &&
        this.multipleSelection[0] != undefined
      ) {
        this.$confirm("只会导出已选择的数据，确定要导出发货表码？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$message({
            type: "success",
            message: "导出成功!",
          });
          this.multipleSelection.forEach(function (order) {
            exprotIds += order.id + "~";
          });
          window.open(
            orderApi.DownlaodSendOrder +
              `?token=${getToken()}` +
              `&ids=${exprotIds}`
          );
        });
      }
    },

    // 删除序列号
    deleteSNumberById(serialNumber) {
      this.$confirm(`您确认要删除序列号${serialNumber.serialNumber}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          serivalNumberApi
            .deleteSerialNumberById(serialNumber)
            .then((response) => {
              this.$message({
                type: "success",
                message: response.message,
              });
              this.getOrderList();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 序列号
    SerivalNumUi(serival, id) {
      this.SerialNumForm.orderId = id;
      if (serival == null || serival == undefined) {
        this.SerivalNumtitle = "新增序列号";
        this.dialogFormVisibleSerivalNum = true;
      } else {
        this.SerivalNumtitle = "更新序列号";
        this.dialogFormVisibleSerivalNum = true;
      }
    },
    saveSerivalNum() {
      this.$refs.SerialNumFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 提交数据给后台
          serivalNumberApi
            .addSerivalNumber(this.SerialNumForm)
            .then((response) => {
              if (response.code == 20000) {
                this.$message({
                  showClose: true,
                  message: response.message,
                  type: "success",
                });
                // 关闭对话框
                this.dialogFormVisibleSerivalNum = false;
                // 刷新表单
                this.getOrderList();
                this.loading = false;
              } else {
                this.$message({
                  showClose: true,
                  message: response.message,
                  type: "error",
                });
                this.loading = false;
              }
            });
        } else {
          // 验证不通过
          this.$message({
            showClose: true,
            message: "表单验证不通过",
            type: "error",
          });
          this.loading = false;
          return false;
        }
      });
    },
    handleImport(response) {
      // 成功;

      if (response.code == 20000) {
        // 成功
        this.$message.success("导入成功");
        this.getOrderList(); // 刷新
      } else {
        this.$message.error(response.message);
      }
    },
    // tabs切喊
    handleClick(tab, event) {
      this.getOrderList();
    },

    // 批量更新状态
    updateStatus(statusCode) {
      let ids = this.multipleSelection.map((order) => order.id);
      if (ids.length > 0) {
        this.$confirm(
          `您确认要批量更新${ids.length}个订单的状态为-${statusCode}?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            orderApi.setOrderStatusByIds(ids, statusCode).then((response) => {
              if (response.code == 20000) {
                this.$message({
                  type: "success",
                  message: response.message,
                });
                this.getOrderList();
              } else {
                this.$message({
                  type: "error",
                  message: response.message,
                });
                this.getOrderList();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消批量更新状态",
            });
          });
      }
    },

    // 修改订单状态
    updateOrderStatus(command) {
      this.$confirm(`您确认要修改状态为 ${command.status}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var UpdateModelAndStatus = {
            model: command.model,
            status: command.status,
          };
          orderApi
            .updateOrderStatus(command.id, UpdateModelAndStatus)
            .then((response) => {
              if (response.code === 20000) {
                this.$message({
                  type: "success",
                  message: response.message,
                });
              } else {
                this.$message({
                  type: "error",
                  message: response.message,
                });
              }
              this.getOrderList();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },

    // 触发下单菜单
    handleCommand(command) {
      this.updateOrderStatus(command);
    },

    // 获取最新的前两条日志
    getNewLogs(logs) {
      var newLogs = [];
      if (logs.length > 2) {
        for (let i = 0; i < 2; i++) {
          newLogs.push(logs[i]);
        }
        return newLogs;
      } else {
        return logs;
      }
    },

    // 添加自定义日志
    openAddlogUi(row) {
      this.userLogForm.id = row.id;
      this.dialogVisibleLog = true;
    },
    addUserLog() {
      if (
        this.userLogForm.types.length == 0 &&
        (this.userLogForm.log == undefined || this.userLogForm.log == null)
      ) {
        this.$message({
          type: "error",
          message: "日志不能为空",
        });
      } else {
        orderLogApi.addLog(this.userLogForm).then((response) => {
          if (response.code == 20000) {
            this.$message({
              type: "success",
              message: response.message,
            });
            // 清空表单数据
            this.userLogForm = {
              types: [],
            };
            this.dialogVisibleLog = false;
            this.getOrderList();
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
      }
    },

    // 获取订单特殊订单个数
    getSpecialOrderNum(logs) {
      var num = 0;

      logs.forEach((item) => {
        if (
          item.log === "补发订单" ||
          item.log === "重复订单" ||
          item.log === "转寄订单"
        ) {
          num += 1;
        }
      });

      return num;
    },

    // 判断订单是否重复
    isExist(orderLogs, model) {
      if (orderLogs.length > 0) {
        if (model === "orderNumber") {
          for (const log of orderLogs) {
            if (log.log === "订单编号重复") {
              return true;
            }
          }
        } else if (model === "userinfo") {
          for (const log of orderLogs) {
            if (log.log === "客户信息重复") {
              return true;
            }
          }
        }
      } else {
        return false;
      }
    },

    // 点击复制提示
    copyMessage() {
      this.$message({
        type: "success",
        message: "复制成功",
      });
    },

    // 获取收货信息
    getAddressInfo(row) {
      var username = row.userName;
      var phone = row.phone;
      var address = row.address;

      return username + "," + phone + "," + address;
    },

    // 发货对话框
    OpenSendGoodsUi() {
      this.sendGoodsList = [];
      for (const goods of this.multipleSelection) {
        var nedeGoodsData = {};

        nedeGoodsData.id = goods.id;
        nedeGoodsData.tradeName = goods.tradeName;
        nedeGoodsData.setMeal = goods.setMeal;
        nedeGoodsData.attachment = goods.attachment;
        nedeGoodsData.serialNumber = this.sumSerialNumbers(goods.serialNumbers);
        nedeGoodsData.trackingNumber = goods.trackingNumber;
        nedeGoodsData.userName = goods.userName;
        nedeGoodsData.phone = goods.phone;
        nedeGoodsData.address = goods.address;
        nedeGoodsData.remark = goods.remark;

        this.sendGoodsList.push(nedeGoodsData);
      }

      this.$nextTick(() => {
        this.initInputDOM();
      });
      this.dialogVisibleLogSendGoods = true;
    },

    // 合并序列号
    sumSerialNumbers(serialNumbers) {
      var sumNum = "";

      if (
        serialNumbers == null ||
        serialNumbers == undefined ||
        serialNumbers.length == 0
      )
        return sumNum;
      serialNumbers.forEach((item) => {
        sumNum += item.serialNumber + "/";
      });

      // 删除最后一个 / 并返回
      return sumNum.substring(0, sumNum.length - 1);
    },

    // 更新运单号
    updateTrackingNumber(order) {
      // 更新序列号
      orderApi.updateTrackingNumber(order).then((response) => {
        if (response.code != 20000) {
          this.$alert(response.message, "运单号异常", {
            type: "warning",
            confirmButtonText: "确定",
            callback: (action) => {
              // 将这一行的序列号清空
              for (const o of this.sendGoodsList) {
                if (o.id === order.id) {
                  o.trackingNumber = "";
                }
              }
            },
          });
        }
      });
    },

    // 更新序列号
    updateSerialNumber(order) {
      serivalNumberApi.addSerialNumber(order).then((response) => {
        if (response.code != 20000) {
          if (response.code === 123456) {
            this.$message({
              type: "error",
              message: response.message,
            });
          } else {
            this.$alert(response.message, "序列号异常", {
              type: "warning",
              confirmButtonText: "确定",
            });
          }
        }
      });
    },

    // 移动光标
    nextFocus(event, row) {
      const index = event.target.getAttribute("data-index");
      const nextIndex = parseInt(index) + 2;
      const length = this.inputDoms.length;
      if (nextIndex < length) {
        this.inputDoms[nextIndex].focus();
      }
    },

    // 获取所有仓库名称
    getAllwareHouseName() {
      warehouseApi.selseAllName().then((response) => {
        this.allwareHouseName = response.data;
      });
    },

    // 打开库存调拨对话框
    openTransferUi() {
      // 选中订单绑定的序列号
      var serialNumbers = [];
      this.multipleSelection.forEach((order) => {
        order.serialNumbers.forEach((serialNumber) => {
          serialNumbers.push(serialNumber.serialNumber);
        });
      });

      this.transferData.serialNumbers = serialNumbers;

      // 需要的数据有，{序列号}

      this.dialogVisibleLogOutWarehouse = true;
    },

    // 获取序列号状态
    getInWarehouseNum() {
      // 获取序列号状态
      // 返回的数据在库，和不在库两组数据{Inwarehouse:[传递的序列号], outWarehouse:[传递的序列号]}
      this.transferLoading = true;
      this.transferData.warehouseId = this.transGoodsForm.outWarehouseId;
      this.transferData.type = true; // 订单序列号

      inventoryApi
        .getInWarehouseSerialNumber(this.transferData)
        .then((response) => {
          if (response.code == 20000) {
            this.transGoodsForm.inWarehouseSerialNumber =
              response.data.inWarehouseSerialNumber;
            this.transGoodsForm.outWarehouseSerialNumber =
              response.data.outWarehouseSerialNumber;
          } else {
            this.$message({ type: "error", message: response.message });
          }

          this.transferLoading = false;
        });
    },

    getTableName(name) {
      if (name === "在库") {
        return (
          name + "(" + this.transGoodsForm.inWarehouseSerialNumber.length + ")"
        );
      } else if (name === "不在库") {
        return (
          name + "(" + this.transGoodsForm.outWarehouseSerialNumber.length + ")"
        );
      }
    },

    // 序列号调拨
    transferSerialNumber() {
      var serialNumbers = [];

      this.transGoodsForm.inWarehouseSerialNumber.forEach((item) => {
        var serialNumber = {};

        serialNumber.orderId = item.orderId;
        serialNumber.serialNumber = item.serialNumber;
        serialNumbers.push(serialNumber);
      });

      var transfer = {
        outWarehouseId: this.transGoodsForm.outWarehouseId,
        saveWarehouseId: this.transGoodsForm.saveWarehouseId,
        serialNumbers: serialNumbers,
        serialNumberStatus: true, // 已出库
        type: true, // 订单
      };

      // 判断是否能调拨
      if (
        transfer.outWarehouseId == null ||
        transfer.outWarehouseId == undefined
      ) {
        this.$message({
          type: "error",
          message: "请选择调出仓库",
        });
      } else if (
        transfer.saveWarehouseId == null ||
        transfer.saveWarehouseId == undefined
      ) {
        this.$message({
          type: "error",
          message: "请选择调入仓库",
        });
      } else if (
        transfer.serialNumbers == null ||
        transfer.serialNumbers == undefined ||
        transfer.serialNumbers.length == 0
      ) {
        this.$message({
          type: "error",
          message: "序列号列表为空",
        });
      } else {
        this.$confirm("此操作会调拨仓库中的商品, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 序列号调拨
          serivalNumberApi.TransferSerialNumber(transfer).then((response) => {
            if (response.code === 20000) {
              this.$message({
                type: "success",
                message: response.message,
              });

              // 关闭对话框
              this.dialogVisibleLogOutWarehouse = false;

              // 刷新
              this.getOrderList();
            } else {
              this.$message({
                type: "error",
                message: response.message,
              });
            }
          });
        });
      }
    },

    updateSerialNumberStatus(row) {
      this.$confirm(`确定要将该序列号的状态设置为-已出库？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 序列号出库
        var serialNumbersAndStatus = {
          serialNumber: row.serialNumber,
          status: true, // 已出库
          type: true, //订单
        };

        serivalNumberApi
          .updateSerialNumber(serialNumbersAndStatus)
          .then((response) => {
            if (response.code === 20000) {
              this.$message({
                type: "success",
                message: response.message,
              });
            } else {
              this.$message({
                type: "warning",
                message: response.message,
              });
            }
            this.getOrderList();
          });
      });
    },

    // 打开批量减库存对话框
    OpenGoodsUi() {
      this.GoodsList = [];
      // 获取指定状态的值
      for (const goods of this.multipleSelection) {
        if (goods.stockStatus === this.seleceStatusCode) {
          this.GoodsList.push(goods);
        }
      }
      this.dialogTableVisibleGoods = true;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 更新库存状态
    updateStockStatus() {
      if (
        this.statusCode == null ||
        this.statusCode == undefined ||
        this.statusCode === ""
      )
        return;

      if (
        this.multipleSelectionGoodsList != null ||
        this.multipleSelectionGoodsList != undefined
      ) {
        // 获取IDS
        let ids = this.multipleSelectionGoodsList.map((order) => order.id);
        this.$confirm(
          `您确认要批量更新${ids.length}个订单的状态为${this.statusCode} ?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          orderApi.updateStockStatus(ids, this.statusCode).then((response) => {
            this.$message({
              type: "success",
              message: response.message,
            });
            this.getOrderList();

            // 关闭对话框
            this.dialogTableVisibleGoods = false;
          });
        });
      }
    },
  },
  created() {
    this.getOrderList();
    this.getAllwareHouseName();
  },

  computed: {
    // 获取商品列表个个型号的数量
    getGoodsListSum() {
      var GoosListSum = {};
      this.multipleSelectionGoodsList.forEach((item) => {
        // 更具+号分割字符串
        var nameList = item.tradeName.split("+");
        nameList.forEach((name) => {
          name = name.trim();
          if (GoosListSum[name] == null || GoosListSum[name] == undefined) {
            GoosListSum[name] = 1;
          } else {
            GoosListSum[name] += 1;
          }
        });
      });

      // this.message 是对 data 中的 message 的引用
      return GoosListSum;
    },
  },
};
</script>

<style scoped>
.el-card {
  margin: 10px;
  font-size: 16px;
}

.el-tag {
  font-size: 16px;
  margin-bottom: 6px;
  margin-right: 4px;
}
</style>
